package bootstrap.liftweb

import _root_.net.liftweb.common._
import _root_.net.liftweb.util._
import _root_.net.liftweb.http._
import _root_.net.liftweb.sitemap._
import _root_.net.liftweb.sitemap.Loc._
import Helpers._
import _root_.net.liftweb.mapper._
import _root_.java.sql.{Connection, DriverManager}
import _root_.com.chessbit.model._
import net.liftweb.mongodb._
import javax.mail.{Authenticator, PasswordAuthentication}

/**
  * A class that's instantiated early and run.  It allows the application
  * to modify lift's environment
  */
class Boot {
  def boot {

    MongoDB.defineDb(
      DefaultMongoIdentifier,
      MongoAddress(MongoHost(), "chessbit")
    ) 

    // add the com.chessbit package to the list packages
    // searched for Snippets, CometWidgets, etc.
    LiftRules.addToPackages("com.chessbit")

    // Update the database schema to be in sync
    //Schemifier.schemify(true, Schemifier.infoF _, User, Game)

    // The locale is either calculated based on the incoming user or
    // based on the http request
    LiftRules.localeCalculator = r => User.currentUser.map(_.locale.isAsLocale).openOr(LiftRules.defaultLocaleCalculator(r))

    // Build SiteMap
    val entries = Menu(Loc("Home", List("index"), "Home")) ::
    Menu(Loc("Game board", List("view"), "View a game"))  :: 
    Menu(Loc("Upload a game", List("file_upload"), "Upload a game"))  :: User.sitemap

    LiftRules.setSiteMap(SiteMap(entries:_*))
    // config an email sender
    configMailer

  }
  
    /*
  * Config mailer
  */
  private def configMailer {

    var isAuth = Props.get("mail.smtp.auth", "false").toBoolean

    Mailer.customProperties = Props.get("mail.smtp.host", "localhost") match {
      case "smtp.gmail.com" =>
        isAuth = true
        Map(
          "mail.smtp.host" -> "smtp.gmail.com",
          "mail.smtp.port" -> "587",
          "mail.smtp.auth" -> "true",
          "mail.smtp.starttls.enable" -> "true"
        )
      case h => Map(
        "mail.smtp.host" -> h,
        "mail.smtp.port" -> Props.get("mail.smtp.port", "25"),
        "mail.smtp.auth" -> isAuth.toString
      )
    }

    if (isAuth) {
      (Props.get("mail.smtp.user"), Props.get("mail.smtp.pass")) match {
        case (Full(username), Full(password)) =>
          Mailer.authenticator = Full(new Authenticator() {
            override def getPasswordAuthentication = new
              PasswordAuthentication(username, password)
          })
        case _ => new Exception("Username/password not supplied for Mailer.")
      }
    }
  }

  
}

